<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API处理工具 - 动态表头显示</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            background-color: #f5f7f9;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eaecef;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        h2 {
            color: #3498db;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }
        textarea {
            width: 100%;
            min-height: 150px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: monospace;
            font-size: 14px;
            resize: vertical;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #2c3e50;
        }
        select, input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: background 0.3s;
        }
        .btn:hover {
            background: #2980b9;
        }
        .btn-secondary {
            background: #95a5a6;
        }
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        .btn-success {
            background: #27ae60;
        }
        .btn-success:hover {
            background: #219653;
        }
        .btn-container {
            text-align: center;
            margin: 20px 0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eaecef;
        }
        th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        tr:hover {
            background-color: #f5f7f9;
        }
        .preview-container {
            margin-top: 20px;
        }
        pre {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        .instructions {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border-left: 4px solid #3498db;
        }
        .instructions h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }
        .instructions ul {
            margin-left: 20px;
        }
        .instructions li {
            margin-bottom: 8px;
        }
        .column-mapping {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .success {
            color: #27ae60;
            font-weight: 600;
        }
        .error {
            color: #e74c3c;
            font-weight: 600;
        }
        .header-preview {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .mapping-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .mapping-row label {
            margin-right: 10px;
            min-width: 100px;
        }
        .mapping-row select {
            flex: 1;
        }
        .hidden {
            display: none;
        }
        .card {
            border: 1px solid #eaecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .card-header {
            font-weight: 600;
            margin-bottom: 10px;
            color: #2c3e50;
        }
        .tag {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 5px;
        }
        .tag-field {
            background: #3498db;
            color: white;
        }
        .tag-type {
            background: #9b59b6;
            color: white;
        }
        .tag-comment {
            background: #27ae60;
            color: white;
        }
        .tag-unknown {
            background: #95a5a6;
            color: white;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-success {
            background-color: #27ae60;
        }
        .status-warning {
            background-color: #f39c12;
        }
        .status-error {
            background-color: #e74c3c;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>API处理工具：动态表头显示</h1>
        
        <div class="instructions">
            <h3>使用说明</h3>
            <ul>
                <li>从Excel或文档中复制表格内容（使用Tab键分隔列）</li>
                <li>将内容粘贴到下方文本区域，工具会自动识别表头</li>
                <li>如果需要，可以手动调整列映射</li>
                <li>点击"解析表格"按钮生成API预览</li>
                <li>确认无误后点击"生成Java实体"</li>
            </ul>
        </div>

        <div class="section">
            <h2>1. 粘贴表格数据</h2>
            <textarea id="tableData" placeholder="请粘贴表格内容（使用Tab分隔列）...">字段名称	数据类型	字段说明	是否必填
id	Long	唯一标识	是
username	String	用户名	是
email	String	邮箱地址	否
createdAt	Date	创建时间	是
active	Boolean	是否激活	是</textarea>
            
            <div class="btn-container">
                <button id="detectHeaderBtn" class="btn">识别表头</button>
            </div>
        </div>

        <div class="section" id="mappingSection" style="display: none;">
            <h2>2. 表头映射</h2>
            <div class="header-preview">
                <p>检测到的表头：</p>
                <div id="headerTags"></div>
            </div>
            
            <div class="card">
                <div class="card-header">映射设置</div>
                <div id="mappingContainer"></div>
            </div>
        </div>

        <div class="btn-container">
            <button id="parseBtn" class="btn">解析表格</button>
        </div>

        <div class="section">
            <h2>3. API预览</h2>
            <div id="apiPreview"></div>
        </div>

        <div class="btn-container">
            <button id="generateBtn" class="btn btn-success">生成Java实体</button>
        </div>

        <div class="section">
            <h2>4. Java实体代码</h2>
            <div class="preview-container">
                <pre id="javaCode"></pre>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const tableData = document.getElementById('tableData');
            const detectHeaderBtn = document.getElementById('detectHeaderBtn');
            const mappingSection = document.getElementById('mappingSection');
            const headerTags = document.getElementById('headerTags');
            const mappingContainer = document.getElementById('mappingContainer');
            const parseBtn = document.getElementById('parseBtn');
            const generateBtn = document.getElementById('generateBtn');
            const apiPreview = document.getElementById('apiPreview');
            const javaCode = document.getElementById('javaCode');
            
            let currentHeaders = [];
            let columnMappings = {};
            let detectedFieldIndex = -1;
            let detectedTypeIndex = -1;
            let detectedCommentIndex = -1;
			let detectedLenIndex = -1;
            let detectedMustIndex = -1;
            
            // 自动识别表头
            detectHeaderBtn.addEventListener('click', function() {
                const data = tableData.value.trim();
                if (!data) {
                    alert('请先粘贴表格数据');
                    return;
                }
                
                const rows = data.split('\n');
                if (rows.length === 0) {
                    alert('表格数据为空');
                    return;
                }
                
                // 获取表头
                currentHeaders = rows[0].split('\t');
                detectColumnMapping(currentHeaders);
                displayHeaderTags(currentHeaders);
                setupColumnMappings(currentHeaders);
                
                // 显示映射区域
                mappingSection.style.display = 'block';
            });
            
            // 检测列映射
            function detectColumnMapping(headers) {
                detectedFieldIndex = -1;
                detectedTypeIndex = -1;
                detectedCommentIndex = -1;
                detectedLenIndex = -1;
                detectedMustIndex = -1;

                headers.forEach((header, index) => {
                    header = header.toLowerCase();
                    
                    if (header.includes('字段名称') || header.includes('名称') ||header.includes('field') || header.includes('name') || header.includes('column')) {
                        detectedFieldIndex = index;
                    }
                    
                    if (header.includes('类型') || header.includes('型') || header.includes('type') || 
  header.includes('class') || header.includes('数据类型')) {
                        detectedTypeIndex = index;
                    }
                    
                    if (header.includes('描述') || header.includes('说明') || header.includes('注释') || 
                        header.includes('comment') || header.includes('description') || header.includes('备注') ||
                        header.includes('字段说明')) {
                        detectedCommentIndex = index;
                    }
					 if (header.includes('长度') || header.includes('size') || header.includes('length')) {
                        detectedLenIndex = index;
                    }
					
					if (header.includes('必填') || header.includes('选填')) {
                        detectedMustIndex = index;
                    }
					
                });
            }
            
            // 显示表头标签
            function displayHeaderTags(headers) {
                headerTags.innerHTML = '';
                headers.forEach((header, index) => {
                    let tagType = 'unknown';
                    
                    if (index === detectedFieldIndex) tagType = 'field';
                    else if (index === detectedTypeIndex) tagType = 'type';
                    else if (index === detectedCommentIndex) tagType = 'comment';
                    else if (index === detectedLenIndex) tagType = 'len';
					else if (index === detectedMustIndex) tagType = 'must';
                    const span = document.createElement('span');
                    span.className = `tag tag-${tagType}`;
                    span.textContent = header;
                    headerTags.appendChild(span);
                });
            }
            
            // 设置列映射
            function setupColumnMappings(headers) {
                mappingContainer.innerHTML = '';
                columnMappings = {};
                
                headers.forEach((header, index) => {
                    const div = document.createElement('div');
                    div.className = 'mapping-row';
                    
                    const label = document.createElement('label');
                    label.textContent = header;
                    
                    const select = document.createElement('select');
                    select.id = `mapping-${index}`;
                    
                    const options = [
                        {value: 'ignore', text: '忽略此列'},
                        {value: 'field', text: '字段名'},
                        {value: 'type', text: '类型'},
                        {value: 'comment', text: '注释'},
						{value: 'len', text: '长度'},
						{value: 'must', text: '必填'}
                    ];
                    
                    options.forEach(opt => {
                        const option = document.createElement('option');
                        option.value = opt.value;
                        option.textContent = opt.text;
                        select.appendChild(option);
                    });
                    
                    // 设置默认选择
                    if (index === detectedFieldIndex) {
                        select.value = 'field';
                    } else if (index === detectedTypeIndex) {
                        select.value = 'type';
                    } else if (index === detectedCommentIndex) {
                        select.value = 'comment';
                    }else if (index === detectedLenIndex) {
                        select.value = 'len';
                    }else if (index === detectedMustIndex) {
                        select.value = 'must';
                    }
                    
                    div.appendChild(label);
                    div.appendChild(select);
                    mappingContainer.appendChild(div);
                    
                    // 存储映射关系
                    columnMappings[index] = select.value;
                    
                    // 添加变化监听
                    select.addEventListener('change', function() {
                        columnMappings[index] = this.value;
                    });
                });
            }
            
            // 解析表格数据
            parseBtn.addEventListener('click', function() {
                const result = parseTableData();
                if (!result) return;
                
                // 显示预览
                displayApiPreview(result);
            });

            // 生成Java实体
            generateBtn.addEventListener('click', function() {
                const result = parseTableData();
                if (!result) return;
                
                // 生成Java代码
                generateJavaCode(result);
            });
            
            // 解析表格数据
            function parseTableData() {
                const data = tableData.value.trim();
                if (!data) {
                    alert('请先粘贴表格数据');
                    return null;
                }

                const rows = data.split('\n');
                if (rows.length < 2) {
                    alert('表格数据至少需要包含表头和一行数据');
                    return null;
                }

                // 获取表头
                const headers = rows[0].split('\t');
                
                // 找出映射为field、type、comment的列索引
                let fieldColumnIndex = -1;
                let typeColumnIndex = -1;
                let commentColumnIndex = -1;
				let lenColumnIndex = -1;
				let mustColumnIndex = -1;
                for (let i = 0; i < headers.length; i++) {
                    if (i in columnMappings) {
                        if (columnMappings[i] === 'field') {
                            fieldColumnIndex = i;
                        } else if (columnMappings[i] === 'type') {
                            typeColumnIndex = i;
                        } else if (columnMappings[i] === 'comment') {
                            commentColumnIndex = i;
                        } else if (columnMappings[i] === 'len') {
                            lenColumnIndex = i;
                        } else if (columnMappings[i] === 'must') {
                            mustColumnIndex = i;
                        }
                    }
                }

                // 解析数据行
                const apiData = [];
                for (let i = 1; i < rows.length; i++) {
                    const cells = rows[i].split('\t');
                    if (cells.length < headers.length) continue;
                    
                    const fieldData = {
                        field: fieldColumnIndex !== -1 ? cells[fieldColumnIndex] : '',
                        type: typeColumnIndex !== -1 ? cells[typeColumnIndex] : '',
                        comment: commentColumnIndex !== -1 ? cells[commentColumnIndex] : '',
						len: lenColumnIndex !== -1 ? cells[lenColumnIndex] : '',
						 must: mustColumnIndex !== -1 ? cells[mustColumnIndex] : ''
                    };
                    
                    if (fieldData.field) {
                        apiData.push(fieldData);
                    }
                }

                return {
                    headers: headers,
                    data: apiData,
                    fieldIndex: fieldColumnIndex,
                    typeIndex: typeColumnIndex,
                    commentIndex: commentColumnIndex,
					lenIndex: lenColumnIndex,
                    mustIndex: mustColumnIndex

                };
            }

            // 显示API预览
            function displayApiPreview(dataParam) {
			
                if (!dataParam || dataParam.data.length === 0) {
                    apiPreview.innerHTML = '<p class="error">未找到有效数据，请检查列映射设置</p>';
                    return;
                }
                var data=dataParam.data;
                let html = '<table>';
                
                // 使用原始表头
                html += '<tr>';
				
                if (dataParam.fieldIndex !== -1) html += `<th>${dataParam.headers[dataParam.fieldIndex]}</th>`;
                if (dataParam.typeIndex !== -1) html += `<th>${dataParam.headers[dataParam.typeIndex]}</th>`;
                if (dataParam.commentIndex !== -1) html += `<th>${dataParam.headers[dataParam.commentIndex]}</th>`;
				if (dataParam.lenIndex !== -1) html += `<th>${dataParam.headers[dataParam.lenIndex]}</th>`;
				if (dataParam.mustIndex !== -1) html += `<th>${dataParam.headers[dataParam.mustIndex]}</th>`;
                html += '</tr>';
                
                data.forEach(item => {
                    html += '<tr>';
                    if (dataParam.fieldIndex !== -1) html += `<td>${item.field}</td>`;
                    if (dataParam.typeIndex !== -1) html += `<td>${item.type}</td>`;
                    if (dataParam.commentIndex !== -1) html += `<td>${item.comment}</td>`;
					if (dataParam.lenIndex !== -1) html += `<td>${item.len}</td>`;
                    if (dataParam.mustIndex !== -1) html += `<td>${item.must}</td>`;

                    html += '</tr>';
                });
                
                html += '</table>';
                apiPreview.innerHTML = html;
            }

            // 生成Java代码
            function generateJavaCode(dataParam) {
                if (!dataParam || dataParam.data.length === 0) {
                    javaCode.textContent = '// 未找到有效数据，请检查列映射设置';
                    return;
                }
                var data=dataParam.data;
                // 获取类名（使用第一个字段名的大写形式）
                const className = data[0].field ? data[0].field.charAt(0).toUpperCase() + data[0].field.slice(1) + 'Entity' : 'ApiEntity';
                
                let code = '/**\n * 自动生成的实体类\n */\n';
                code += `public class ${className} {\n\n`;
                
                data.forEach(item => {
                    // 添加注释
                    if (item.comment) {
                        code += `    /**\n     * ${item.comment}\n     */\n`;
                    }
                    
                    // 添加字段
                    code += `    private ${item.type} ${item.field};\n\n`;
                });
                
                // 添加getter和setter方法
                data.forEach(item => {
                    const capitalizedField = item.field.charAt(0).toUpperCase() + item.field.slice(1);
                    
                    // Getter方法
                    code += `    public ${item.type} get${capitalizedField}() {\n`;
                    code += `        return this.${item.field};\n`;
                    code += '    }\n\n';
                    
                    // Setter方法
                    code += `    public void set${capitalizedField}(${item.type} ${item.field}) {\n`;
                    code += `        this.${item.field} = ${item.field};\n`;
                    code += '    }\n\n';
                });
                
                code += '}';
                
                javaCode.textContent = code;
            }

            // 初始时自动识别表头
            setTimeout(() => {
                detectHeaderBtn.click();
                parseBtn.click();
            }, 500);
        });
    </script>
</body>
</html>